package com.tea.controller;

import com.tea.Model.User;
import com.tea.Model.dto.LoginDTO;
import com.tea.constans.OpenId;
import com.tea.service.LoginService;
import com.tea.service.UserService;
import com.tea.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.spel.ast.OpInc;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Resource
    private LoginService loginService;
    
    @Resource
    private OpenId openIdValidator;

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginDTO code) {
        return loginService.login(code);
    }

    @GetMapping("/getUserInfo")
    public Result<?> getCurrentUser() {
        // 从安全上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 从认证信息中获取 openid（存储在 JWT 的 subject 中）
        String openid = authentication.getName();
        log.info("openid: {}", openid);
        // 检查用户是否已存在，如果不存在则创建新用户
        User existingUser = userService.getUserByOpenId(openid);
        if (existingUser == null) {
            // 创建新用户
            User newUser = new User();
            newUser.setOpenId(openid);
            newUser.setRole(0); // 默认为普通用户
            newUser.setStatus(1); // 启用状态
            newUser.setDeleted(0); // 未删除
            newUser.setCreateTime(LocalDateTime.now());
            newUser.setUpdateTime(LocalDateTime.now());

            boolean saved = userService.save(newUser);
            if (saved) {
                log.info("新用户创建成功，openid: {}", openid);
                existingUser = newUser; // 设置当前用户为新创建的用户
            } else {
                log.error("新用户创建失败，openid: {}", openid);
            }
        } else {
            // 更新现有用户的登录时间
            existingUser.setUpdateTime(LocalDateTime.now());
            userService.updateById(existingUser);
            log.info("用户登录成功，openid: {}", openid);
        }
        //构建返回结果，isAdmin-是否为管理员角色
        HashMap<String, Object> map = new HashMap<>();
        // 根据用户的role字段判断是否为管理员：1-管理员，0-普通用户
        if (existingUser != null && existingUser.getRole() != null && existingUser.getRole() == 1) {
            map.put("isAdmin", true);
        } else {
            map.put("isAdmin", false);
        }
        log.info("用户openid: {}",openid);
        return Result.success(map);
    }

    /**
     * 检查登录状态
     * 如果token有效，返回成功；如果无效，JWT过滤器会自动返回401
     */
    @GetMapping("/checkLogin")
    public Result<?> checkLoginStatus() {
        // 从安全上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.isAuthenticated()) {
            String openid = authentication.getName();

            // 检查用户是否已存在，如果不存在则创建新用户
            User existingUser = userService.getUserByOpenId(openid);
            if (existingUser == null) {
                // 创建新用户
                User newUser = new User();
                newUser.setOpenId(openid);
                newUser.setStatus(1); // 启用状态
                newUser.setDeleted(0); // 未删除
                newUser.setCreateTime(LocalDateTime.now());
                newUser.setUpdateTime(LocalDateTime.now());

                boolean saved = userService.save(newUser);
                if (saved) {
                    log.info("新用户创建成功，openid: {}", openid);
                } else {
                    log.error("新用户创建失败，openid: {}", openid);
                }
            } else {
                // 更新现有用户的登录时间
                existingUser.setUpdateTime(LocalDateTime.now());
                userService.updateById(existingUser);
                log.info("用户登录成功，openid: {}", openid);
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("isLoggedIn", true);
            map.put("openid", openid);
            return Result.success(map);
        } else {
            return Result.error(401, "未登录");
        }
    }
}